//
//  File.swift
//
//
//  Created by didi on 2022/9/8.
//

import MolecularObjects
import Vapor

fileprivate let scope = "web.menus"

extension Request {
    func menu(_ key: String) -> MenuContext? {
        globals.get(key, scope: scope)
    }
}

struct MolecularMenuMiddleware: AsyncMiddleware {
    func respond(to request: Request, chainingTo next: AsyncResponder) async throws -> Response {
        let menus: [Menu] = try await request.invokeAllFlatAsync(.menu)
        for menu in menus {
            let items = menu.items
                .sorted { $0.priority > $1.priority }
                .map {
                    LinkContext(label: $0.label,
                                path: $0.url,
                                absolute: true,
                                isBlank: $0.isBlank,
                                dropLast: 0,
                                priority: $0.priority,
                                permission: $0.permission,
                                style: .default)
                }
            request.globals.set(menu.key, value: MenuContext(key: menu.key, name: menu.name, items: items), scope: scope)
        }

        return try await next.respond(to: request)
    }
}
